#!/usr/bin/python3

import threading
import time

from FenciForComp import FenciForComp
from SearchAndFenci import SearchAndFenci
from dataPath import resultdirBasepath

class compThread (threading.Thread):
    def __init__(self, threadID, name, flag, searchLog, seedKeyword, midkeynum, mutex):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        #用于判断用哪种分词方法
        self.flag = flag
        #继续用清洗完的数据
        self.searchLog = searchLog
        #种子关键字，虽然没什么大用，但用来做提示和命名
        self.seedKeyword = seedKeyword
        # 这个是根据用户选取的中介关键字的数量传入进行求取竞争关键字的前多少个
        self.midkeynum = midkeynum
        # 这个是用来统计竞争关键字的竞争相关性
        self.dic = {}
        self.mutex = mutex
    def run(self):
        ###start_time = time.time()
        print("开始竞争关键字求取线程：" + self.name + "并处理---" + self.seedKeyword + "---的竞争关键字")
        #这个打开中介关键字文件
        midkeysfile = open(resultdirBasepath + self.seedKeyword + "\\MidKey.txt", 'r', encoding='utf-8')
        #创建中介关键字字典midkeydic
        midkeydic = {}
        for i in range(int(self.midkeynum)):
            #这是一个字符串列表，但是只有键值两个值
            tempkeyvalue = midkeysfile.readline().split()
            #字典存入键值对
            midkeydic[str(tempkeyvalue[0])] = int(tempkeyvalue[1])
        fenciforcomp = FenciForComp(midkeydic)
        midkeysfile.close()
        ###end_time = time.time()
        ###print("中介词读入创建字典时间开销为{:.4f}秒".format(end_time - start_time))
        for index, i in enumerate(self.searchLog):
            if(index%10000==0):
                if(index==0):
                    start_time = time.time()
                end_time = time.time()
                print("处理中介关键字一万条数据时间开销为{:.4f}秒".format(end_time - start_time))
                start_time = time.time()
            temp = i.split()
            # temp中保存了文件中的一行按照空格进行分割后得到的字符串列表，下面需要遍历列表中每个字符串 找到与我们输入的种子关键字匹配的字符串并输出
            for j in temp:
                j = j.decode('UTF-8')
                # 直接传入整个字典进去，这是一个重要的优化，不然就要循环分词，效率很低
                for key in midkeydic:
                    if(key in j):
                        if int(self.flag) == 1:
                            fenciforcomp.jiebafenci(j, self.seedKeyword)
                        # elif int(flag) == 2:
                        #    pkusegfenci(j, self.seedKeyword, midkeydic)
                        elif int(self.flag) == 3:
                            fenciforcomp.thulacfenci(j, self.seedKeyword, midkeydic)
                        # elif int(self.flag) == 4:
                        #    fenciforcomp.pyhanlpfenci(j, self.seedKeyword, midkeydic)
                        else:
                            fenciforcomp.jiebafenci(j, self.seedKeyword, midkeydic)
        print("已经完成所有与---"+self.seedKeyword+"---有关的竞争关键字计算，下面开始把结果写入文件并退出线程：" + self.name)
        fenciforcomp.outputComp(self.seedKeyword)






